package com.weharvest.edu.interceptor;

import com.weharvest.edu.annotation.MenuAnnotion;
import com.weharvest.edu.annotation.PermissionAnnotion;
import com.weharvest.edu.dao.mapper.InterceptorDaoMapper;
import com.weharvest.edu.entity.between.BackstageRoleMenuPermission;
import com.weharvest.edu.enums.CommonEnums;
import com.weharvest.edu.enums.ResultEnum;
import com.weharvest.edu.utlis.ResponseUtil;
import com.weharvest.edu.utlis.SessionUtil;
import net.minidev.json.JSONObject;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 权限验证
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private InterceptorDaoMapper interceptorDaoMapper;

    /**
     * 拦截前端token请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //表示不拦截请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获取菜单值
        MenuAnnotion menuAnnotionValue = handlerMethod.getMethodAnnotation(MenuAnnotion.class);
        if (null == menuAnnotionValue) {
            //是否还有类注解
            menuAnnotionValue = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), MenuAnnotion.class);
            if (null == menuAnnotionValue) {
                return true;
            }
        }
        //获取操作资源值
        PermissionAnnotion permissionValue = handlerMethod.getMethodAnnotation(PermissionAnnotion.class);
        if (null == permissionValue) {
            return true;
        }
        System.out.println("用户真实ip：" + getIpAddress(request) + ",登录时间:" + new Date());
        JSONObject jsonObject = new JSONObject();
        //检验是否有权限通过
        String uid = SessionUtil.getSession(request, "uid");
        String organizationId = SessionUtil.getSession(request, "organizationId");
        if (!check(permissionValue.value(), menuAnnotionValue.value(), uid,organizationId)) {
            jsonObject.put("code", ResultEnum.AUTH_ERROR.getCode());
            jsonObject.put("msg", ResultEnum.AUTH_ERROR.getMsg());
            ResponseUtil.wirteResponseMsg(jsonObject, response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


    /**
     * 获取真实ip
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    //查询该角色是否有菜单和权限操作。
    private boolean check(String permissionValue, String menuValue, String userId,String organizationId) {
        BackstageRoleMenuPermission brmp = new BackstageRoleMenuPermission();
        Map<String,Object> params = new HashMap<>();
        params.put("brmpPermissionId",permissionValue);
        params.put("brmpMenuId", menuValue);
        params.put("buUserId",userId);
        params.put("buOrganizationId",organizationId);
        params.put("brState",CommonEnums.state.STATE_AVAILABLE.getCode());
        params.put("brFlag", CommonEnums.flag.FLAG_AVAILABLE.getCode());
        BackstageRoleMenuPermission backstageRoleMenuPermission
                =interceptorDaoMapper.queryHavePermission(params);
        if (null == backstageRoleMenuPermission) {
            return false;
        }
        return true;
    }
}
